package org.csu.demo.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import org.csu.demo.common.CommonResponse;
import org.csu.demo.domain.User;
import org.csu.demo.service.UserService;
import org.csu.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
public class TokenController {

    @Autowired
    private UserService userService;

    @Autowired
    JwtUtil jwtUtil;

    @PostMapping("/tokens")
    public CommonResponse<String> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        CommonResponse<User> result = userService.login(username, password);
        if(result.isSuccess()){
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",username);
            String token = jwtUtil.genToken(claims);
            return CommonResponse.createForSuccess(token);
        }else{
            return CommonResponse.createForError();
        }
    }
}
